package ourfilter;

import interfaces.Readable;
import interfaces.Writeable;

import java.awt.List;
import java.io.StreamCorruptedException;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

import pipes.Pipe;
import TransferObjekts.Line;

import filter.AbstractFilter;

public class SortLinesFilter extends AbstractFilter<Line, Line> {

	private Readable<Line> in;
	private Writeable<Line> out;
	private ArrayList<Line> linelist = new ArrayList<Line>();
	private Iterator<Line> it = null;
	private boolean hasSorted = false;

	public SortLinesFilter(Pipe<Line> in, Pipe<Line> out)
			throws InvalidParameterException {
		super(in, out);
		in.setOut(this);
		out.setIn(this);
		this.in = in;
		this.out = out;
	}

	private void fillSortLines() throws StreamCorruptedException{
		Line l = null;
		do {
			l = in.read();
			linelist.add(l);
		}while (l != null);
		linelist.remove(linelist.size() -1);
		Collections.sort(linelist);
	}
	
	@Override
	public Line read() throws StreamCorruptedException {
		if(linelist.size() == 0){
			fillSortLines();
			it = linelist.iterator();
		}
		if(it.hasNext()){
			return it.next();
		}else{
			return null;
		}
	}

	@Override
	public void write(Line line) throws StreamCorruptedException {
		if(line != null){
			linelist.add(line);
		}else{
			if(hasSorted == false){
				Collections.sort(linelist);
				hasSorted = true;
				it = linelist.iterator();
			}
			while(it.hasNext()){
				out.write(it.next());
			}
			out.write(null);
		}
	}

	@Override
	public void run() {
	}

}
